package com.xinjian.jianba.controller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xinjian.jianba.dto.CheckCodeDto;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.SmsService;
import com.xinjian.jianba.service.ValidatorService;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.LogBuilder;
import com.xinjian.jianba.utils.ModuleEnum;

@RestController
@RequestMapping("/api/v3/jianba/sms")
public class SmsController extends AbstractController {
	private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);

	@Autowired
	private ValidatorService validatorService;
	@Autowired
	private SmsService smsService;

	/**
	 * 发送短信
	 *
	 */
	@PostMapping(value = { "/send" })
	public String register(@RequestBody CheckCodeDto checkCodeDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.SMS, "发送验证码,参数 checkCodeDto={}"), JsonUtil.getJsonString(checkCodeDto));
		if (checkCodeDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}
		try {
			validatorService.valid(checkCodeDto);
			smsService.sendSms(checkCodeDto.getMobile(), checkCodeDto.getType(), checkCodeDto.getUserId());
			return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		} catch (Exception e) {
			LOGGER.info("----error---" + e);
			return this.responseClientJsonData(ResponseCode.ERROR,  e.getMessage());
		}

	}

	/**
	 * 校验短信验证码是否正确
	 *
	 */
	@PostMapping(value = { "/checkCode" })
	public String checkCode(@RequestBody CheckCodeDto checkCodeDto) {
		LOGGER.info(LogBuilder.build(ModuleEnum.SMS, "校验短信验证码,参数 checkCodeDto={}"), JsonUtil.getJsonString(checkCodeDto));
		if (checkCodeDto == null) {
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, ResponseCode.PARAM_ERROR_MSG);
		}

		Map<String, Object> map = null;
		try {
			map = smsService.checkCode(checkCodeDto);

		} catch (Exception e) {
			LOGGER.info("----checkCode---" + e.getStackTrace());
			return this.responseClientJsonData(ResponseCode.ERROR,  e.getMessage());
		}
		return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, map);

	}

}
